package com.ithinks.flow.common.utils.middleware.rabbitMQ.Routing;

import com.ithinks.flow.common.utils.middleware.rabbitMQ.ConnectionUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description Routing模式：队列在绑定交换机时需要指定routing key
 * @ClassName Router
 * @Author MR.LI
 * @date 2020.11.25 19:31
 */
public class Router_Producer {

    //定义队列名称
    private static final String QUEUE_INFORM_EMAIL = "queue_info_email";

    private static final String QUEUE_INFORM_SMS = "queue_info_sms";

    //指定交换机名称
    private static final String EXCHANGE_ROUTING_INFORM ="exchange_routing_inform";

    //连接配置参数
    private static String IP = "localhost";
    //端口
    private static int PORT = 5672;
    //虚拟机IP，默认/
    private static String VHOST = "/";
    //队列名称
    private static String USERNAME = "guest";

    private static String PASSWORD = "guest";


    public static void main(String[] args) {

        Connection connection = ConnectionUtils.getConnection(IP,PORT,VHOST,USERNAME,PASSWORD);
        Channel channel = null;

        try {
            channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_ROUTING_INFORM, BuiltinExchangeType.DIRECT);
            channel.queueDeclare(QUEUE_INFORM_EMAIL,true,false,false,null);
            channel.queueDeclare(QUEUE_INFORM_SMS,true,false,false,null);
            channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_ROUTING_INFORM,QUEUE_INFORM_EMAIL);
            channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_ROUTING_INFORM,QUEUE_INFORM_SMS);

            //发送email
            for(int i=0; i<10; i++)
            {
                String message = "email info to use " + i;
                channel.basicPublish(EXCHANGE_ROUTING_INFORM,QUEUE_INFORM_EMAIL,null,message.getBytes());
                System.out.println("send message is :'"+message +"'");
            }
            //发送sms
            for(int i=0; i<10; i++)
            {
                String message = "sms info to use " + i;
                channel.basicPublish(EXCHANGE_ROUTING_INFORM,QUEUE_INFORM_SMS,null,message.getBytes());
                System.out.println("send message is :'"+message +"'");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(channel != null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }

            }
           ConnectionUtils.closeConnection(connection);
        }
    }
}
